package com.jlkf.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jlkf.dao.VideoDao;
import com.jlkf.pojo.TblLesson;
import com.jlkf.service.BackCourseInfoService;
import com.jlkf.service.VideoService;
import com.platform.server.response.response.pojo.ReturnData;
import com.platform.server.util.DateUtil;
import com.platform.server.util.HttpClientUtils;
import com.platform.server.util.StringTools;
import com.platform.server.util.UUIDUtil;
import com.platform.server.util.excel.ExcelUtil;


@Controller
@RequestMapping("/video")
public class VideoController {
	
	@Autowired
	private VideoService videoService;
	@Autowired
	private VideoDao videoDao;
	
	@Autowired
	private BackCourseInfoService backCourseInfoService;
	
	/**
	 * 查看视频列表
	 */
	@ResponseBody
	@RequestMapping("/selectVideoList")
	public Object selectVideoList(String startTime,String endTime,String courseName,Integer id,Integer pageNumber,Integer pageSize,String type){
		if(pageNumber == null) pageNumber = 1;
		if(pageSize == null) pageSize = 10;
		Map<String, Object> map = new HashMap<String,Object>();
		if(!StringTools.isEmpty(startTime)){
			map.put("startTime", startTime);
		}
		if(!StringTools.isEmpty(endTime)){
			map.put("endTime", endTime);
		}
		if(!StringTools.isEmpty(courseName)){
			map.put("courseName", courseName);
		}
		if(id != null){
			map.put("id", id);
			ModelAndView modelAndView = new ModelAndView();
			if("1".equals(type)){
				modelAndView.setViewName("jsp/videoManager/videoDetailUpdate");
			}else{
				modelAndView.setViewName("jsp/videoManager/videoDetail");
			}
			List<Map<String, Object>> lists = videoService.selectVideoList(map);
			modelAndView.addObject("result", lists.get(0));
			return modelAndView;
		}
		PageHelper.startPage(pageNumber, pageSize);
		List<Map<String, Object>> lists = videoService.selectVideoList(map);
		PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(lists);
		return new ReturnData(lists,pageInfo.getPages(),(int)pageInfo.getTotal(),200,"视频列表");
	}
	
	/**
	 * 删除视频
	 */
	@ResponseBody
	@RequestMapping("/deleteVideo")
	public Object deleteVideo(String id){
		int flag = videoService.deleteVideo(id);
		if(flag > 0){
			return new ReturnData(200,"删除成功");
		}else{
			return new ReturnData(500,"删除失败");
		}
	}
	
	/**
	 * 添加视频
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping("/insertVideo")
	public Object addCharpter(String title,String get_integral,String get_growth_value,String url,String key,String G_LESSON_MONEY,String G_LESSON_INTEGEAL,String freeUrl,String size,
			String teacher_id,String teacher_name,String content) throws Exception {
		String getTime = "http://p7dbvgmbj.bkt.clouddn.com/" + key;
		String string = HttpClientUtils.get(getTime + "?avinfo");
		Map<?, ?> jsonToMap = StringTools.jsonToMap(string);
		Map<?, ?> object = (Map<?, ?>) jsonToMap.get("format");
		//视频时长，单位为秒
		Double duration = Double.parseDouble(object.get("duration").toString());
		Map<String,Object> map = new HashMap<>();
		Double sizes = Double.parseDouble(size) / 1024 / 1024;
		map.put("video_size", sizes.intValue()  + "MB");
		map.put("title", title);
		map.put("get_integral", get_integral);
		map.put("get_growth_value", get_growth_value);
		map.put("url", url);
		map.put("G_LESSON_DURATION", duration.intValue());
		map.put("G_LESSON_MONEY", G_LESSON_MONEY);
		if("0".equals(G_LESSON_MONEY)){
			map.put("G_LESSON_INTEGEAL", 0);
		}else{
			map.put("G_LESSON_INTEGEAL", G_LESSON_INTEGEAL);
		}
		map.put("teacher_id", teacher_id);
		map.put("teacher_name", teacher_name);
		map.put("freeUrl", freeUrl);
		map.put("content", content);
		if("0".equals(G_LESSON_MONEY)){
			map.put("G_LESSON_IS_FEE", 2);
		}else{
			map.put("G_LESSON_IS_FEE", 1);
		}
		String high_definition = HttpClientUtils.get("http://120.79.157.154:8899/hqsm-oa/qiniu/transcoding/?key=" + key + "&type=1");
		String standard_definition = HttpClientUtils.get("http://120.79.157.154:8899/hqsm-oa/qiniu/transcoding/?key=" + key + "&type=2");
		map.put("high_definition", high_definition);
		map.put("standard_definition", standard_definition);
		int flag =  videoService.insertVideo(map);
		if(flag > 0){
			return new ReturnData(200,"添加成功");
		}else{
			return new ReturnData(500,"添加失败");
		}
	}
	
	/**
	 * 编辑视频
	 */
	@ResponseBody
	@RequestMapping("/updateVideo")
	public Object updateVideo(String title,String get_integral,String get_growth_value,String url,String key,String G_LESSON_MONEY,String G_LESSON_INTEGEAL,String freeUrl,String size,
			String teacher_id,String teacher_name,String G_ID,String content) throws Exception {
		Map<String,Object> map = new HashMap<>();
		if(!StringTools.isEmpty(url) && !StringTools.isEmpty(key)){
			String getTime = "http://p7dbvgmbj.bkt.clouddn.com/" + key;
			String string = HttpClientUtils.get(getTime + "?avinfo");
			Map<?, ?> jsonToMap = StringTools.jsonToMap(string);
			Map<?, ?> object = (Map<?, ?>) jsonToMap.get("format");
			//视频时长，单位为秒
			Double duration = Double.parseDouble(object.get("duration").toString());
			Double sizes = Double.parseDouble(size) / 1024 / 1024;
			map.put("video_size", sizes.intValue()  + "MB");
			map.put("url", url);
			map.put("G_LESSON_DURATION", duration.intValue());
			String high_definition = HttpClientUtils.get("http://120.79.157.154:8899/hqsm-oa/qiniu/transcoding/?key=" + key + "&type=1");
			String standard_definition = HttpClientUtils.get("http://120.79.157.154:8899/hqsm-oa/qiniu/transcoding/?key=" + key + "&type=2");
			map.put("high_definition", high_definition);
			map.put("standard_definition", standard_definition);
  		}
		if(!StringTools.isEmpty(teacher_id) && !StringTools.isEmpty(teacher_name)){
			map.put("teacher_id", teacher_id);
			map.put("teacher_name", teacher_name);
  		}
		//查看视频详情
		Map<String, Object> videoInfo = videoDao.selectVideoInfo(Integer.parseInt(G_ID));
		if(videoInfo != null && (Double)videoInfo.get("G_LESSON_MONEY") != Double.parseDouble(G_LESSON_MONEY)){
			//查看该视频的有关课程
			List<Map<String, Object>> courseList = videoDao.selectCourseList(G_ID);
			for(int i = 0;i < courseList.size();i++){
				Double money = (Double)courseList.get(i).get("G_COURSE_MONEY") - (Double)videoInfo.get("G_LESSON_MONEY") + Double.parseDouble(G_LESSON_MONEY);
				//修改课程信息
				Map<String,Object> hashMap = new HashMap<>();
				hashMap.put("G_ID",courseList.get(i).get("G_ID"));
				hashMap.put("G_COURSE_MONEY",money);
				if(money == 0){
					hashMap.put("G_IS_FEE", 2);
				}else{
					hashMap.put("G_IS_FEE", 1);
				}
				backCourseInfoService.updateCourse(hashMap);
			}
		}
		if(videoInfo != null && (Integer)videoInfo.get("G_LESSON_INTEGEAL") != Integer.parseInt(G_LESSON_INTEGEAL)){
			//查看该视频的有关课程
			List<Map<String, Object>> courseList = videoDao.selectCourseList(G_ID);
			for(int i = 0;i < courseList.size();i++){
				Integer integeal = (Integer)courseList.get(i).get("G_COURSE_INTEGEAL") - (Integer)videoInfo.get("G_LESSON_INTEGEAL") + Integer.parseInt(G_LESSON_INTEGEAL);
				//修改课程信息
				Map<String,Object> hashMap = new HashMap<>();
				hashMap.put("G_ID",courseList.get(i).get("G_ID"));
				hashMap.put("G_COURSE_INTEGEAL",integeal);
				backCourseInfoService.updateCourse(hashMap);
			}
		}
		map.put("title", title);
		map.put("get_integral", get_integral);
		map.put("get_growth_value", get_growth_value);
		map.put("G_LESSON_MONEY", G_LESSON_MONEY);
		map.put("G_LESSON_INTEGEAL", G_LESSON_INTEGEAL);
		map.put("freeUrl", freeUrl);
		map.put("G_ID", Integer.parseInt(G_ID));
		map.put("content", content);
		if(0 == Double.parseDouble(G_LESSON_MONEY)){
			map.put("G_LESSON_IS_FEE", 2);
		}else{
			map.put("G_LESSON_IS_FEE", 1);
		}
		int flag =  videoService.updateVideo(map);
		if(flag > 0){
			return new ReturnData(200,"编辑成功");
		}else{
			return new ReturnData(500,"编辑失败");
		}
	}
	
	/**
	 * 查看视频名称是否已经存在
	 */
	@ResponseBody
	@RequestMapping("/selectVideoName")
	public Object selectVideoName(String G_LESSON_NAME){
		int flag = videoService.selectVideoName(G_LESSON_NAME);
		if(flag > 0){
			return new ReturnData(100,"该视频已经存在！");
		}else{
			return new ReturnData(200,"成功");
		}
	}
	
	/*@ResponseBody
	@RequestMapping("test1")
	public Object test1() throws Exception{
		List<Map<String, Object>> lists = videoDao.selectVideoList(new HashMap<>());
		for(int i = 0;i < lists.size();i++){
			if(lists.get(i).get("standard_definition") == null && lists.get(i).get("high_definition") == null){
				String path = lists.get(i).get("G_LESSON_PATH").toString();
				path = path.substring(23, path.length());
				Long id = (Long)lists.get(i).get("G_ID");
				String high_definition = HttpClientUtils.get("http://120.79.157.154:8899/hqsm-oa/qiniu/transcoding/?key=" + path + "&type=1");
				String standard_definition = HttpClientUtils.get("http://120.79.157.154:8899/hqsm-oa/qiniu/transcoding/?key=" + path + "&type=2");
				Map<String,Object> map = new HashMap<>();
				map.put("id", id);
				map.put("high_definition", high_definition);
				map.put("standard_definition", standard_definition);
				int flag = videoDao.updateVideo(map);
				System.out.println(flag);
			}
		}
		return "成功";
	}*/
	
	/**
   * 导入视频
   */
	@ResponseBody
    @RequestMapping("/readExcelVideo") 
    public Object readExcel(@RequestParam(value="excelFile") MultipartFile file,HttpServletRequest request) throws Exception{
		ModelAndView ModelAndView = new ModelAndView();
		List<TblLesson> newlist = new ArrayList<>();
		try {
	        //判断文件是否为空         
	        String name = file.getOriginalFilename();  
	        long size = file.getSize();  
	        if(name == null || ExcelUtil.EMPTY.equals(name) && size==0){  
	          ReturnData  ReturnData =  new ReturnData("文件为空"); 
	        }  
	        //读取Excel数据到List中  
	        List<ArrayList<String>> list = new excelController().readExcel(file);  
	        if(list == null) {
	        	//ReturnData ReturnData = new ReturnData(200,"成功导入" + newlist.size() + "条数据");
	            //ModelAndView.addObject("ReturnData", ReturnData);
	            request.setAttribute("nums", newlist.size() + "");
	            ModelAndView.setViewName("jsp/videoManager/videoList");
	            return ModelAndView;
	        }
	        for (int i = 0; i < list.size(); i++) {
	    	   ArrayList<String> arrayList = list.get(i);
	    	   TblLesson record = new TblLesson();
		       record.setgLessonName(arrayList.get(0));
		       if(Double.parseDouble(arrayList.get(1)) > 0){
		    	   record.setgLessonIsFee(1);
		       }else{
		    	   record.setgLessonIsFee(2);
		       }
		       record.setgLessonMoney(Double.parseDouble(arrayList.get(1)));
		       record.setgLessonIntegeal(Integer.parseInt(arrayList.get(2)));
		       record.setGetIntegral(arrayList.get(3));
		       record.setGetGrowthValue(arrayList.get(4));
		       record.setgLessonDuration("0");
		       record.setContent(arrayList.get(6));
		       //根据老师名称查询老师信息
		       Map<String, Object> teacehrInfo = videoDao.selectTeacherInfo(arrayList.get(5));
		       record.setTeacherName(teacehrInfo.get("G_NAME").toString());
		       record.setTeacherId(Integer.parseInt(teacehrInfo.get("G_ID").toString()));
		       ReturnData insert = videoService.readExcel(record);
	           if(insert.getCode() == 200) {
	               newlist.add(record);
	           }
	       }
	       //ReturnData ReturnData = new ReturnData(200,"成功导入"+newlist.size()+"条数据");
	       //ModelAndView.addObject("ReturnData", ReturnData);
	       request.setAttribute("nums", newlist.size() + "");
	       ModelAndView.setViewName("jsp/videoManager/videoList");
	       return ModelAndView; 
		} catch (Exception e) {
			ReturnData ReturnData = new ReturnData(200,"成功导入" + newlist.size() + "条数据");
            ModelAndView.addObject("ReturnData", ReturnData);
            ModelAndView.setViewName("jsp/videoManager/videoList");
            return ModelAndView;
		}
    }
}
